<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

// 引入TP的数据库类
use think\Db;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Privatesea extends Backend
{

    /**
     * Business模型对象
     * @var \app\common\model\Business\Business
     */
    protected $model = null;

    // 当前是否为关联查询
    protected $relationSearch = true;

    protected $dataLimit = 'personal'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'adminid'; //数据关联字段,当前控制器对应的模型表中必须存在该字段

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Business.Business');
        $this->RegionModel = model('Region');
        $this->Visitmodel = model('Business.Visit');
        $this->Sourcemodel = model('Business.Source');
        $this->Receivemodel = model('Business.Receive');
        $this->Adminmodel = model('Business.Admin');
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("dealList", $this->model->getDealList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $ids = $this->auth->id;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            //查询总数
            $total = $this->model
                ->where($where)
                ->count();

            //查询数据
            $list = $this->model
                ->with(['source', 'visit', 'admin'])
                ->where(['business.adminid' => $ids])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详细
     */
    public function info($ids = 0)
    {
        $businlist = $this->model
            ->with(['source', 'visit'])
            ->where(['business.id' =>  $ids])
            ->find();

        // 赋值
        $this->view->assign([
            'businlist' => $businlist,
        ]);
        return $this->view->fetch();
    }

    /**
     * 回收
     */
    public function recovery($ids = 0)
    {
        $applyid = $this->auth->id;
        if ($this->request->isAjax()) {
            // 执行更新语句
            $result = Db::name('business')->where(['id' => ['in', $ids]])->update(['adminid' => null]);

            $data = [
                'applyid' => $applyid,
                'busid' => $ids,
                'applytime' => time(),
                'status' => 'recovery',
            ];

            $recovery = $this->Receivemodel->save($data);

            // 判断是否回收成功
            if ($result) {
                $this->success();
                exit;
            } else {
                $this->error(__('回收失败'));
                exit;
            }

            // 判断是否领取表更新成功
            if ($recovery) {
                $this->success();
                exit;
            } else {
                $this->error(__('领取表更新失败'));
                exit;
            }
        }
    }

    /**
     * 软删除方法
     */
    public function del($ids = 0)
    {
        // where in 语句 列表查询
        $rows = $this->model->where(['id' => ['in', $ids]])->select();

        if (!$rows) {
            $this->error('暂无数据');
            exit;
        }

        // 直接软删除
        $result = $this->model->destroy($ids);

        if ($result === FALSE) {
            $this->error('删除用户失败');
            exit;
        } else {
            $this->success();
            exit;
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        $source = $this->Sourcemodel->order('id asc')->column('id,name');
        $ids = $this->auth->id;
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 获取请求中 row 名称的数组元素 row == row[] /a类型 == array
            $params = $this->request->param('row/a');
            $region = $params['region'];

            
            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'adminid' => $ids
            ];

            // 判断地区是否为空
            if(!empty($region))
            {
                // 字符串转换为数组
                // 转换为数组，并获取到最后一个元素
                $RegionList = explode('/', $region);
                $last = array_pop($RegionList);

                // 找出对应的地区码
                $path = $this->RegionModel->where(['name' => $last])->value('parentpath');

                // 字符串转换为数组
                $RegionCode = explode(',',$path);

                $data['province'] = isset($RegionCode[0]) ? $RegionCode[0] : '';
                $data['city'] = isset($RegionCode[1]) ? $RegionCode[1] : '';
                $data['district'] = isset($RegionCode[2]) ? $RegionCode[2] : '';
            }

            // 插入语句
            $result = $this->model->validate('common/Business/Business.Privatesea')->save($data);

            if ($result === FALSE) {
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success();
                exit;
            }
        }
        // 将生成好的select下拉框赋值到模板
        $this->view->assign('source', build_select('row[sourceid]', $source, [], ['class' => 'form-control selectpicker']));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = 0)
    {
        // 进来，先要根据id查询这个客户是否存在
        $business = $this->model->find($ids);
        $source = $this->Sourcemodel->order('id asc')->column('id,name');

        if(!$business)
        {
            $this->error('客户不存在');
            exit;
        }

        // 赋值
        $this->view->assign([
            'business' => $business,
        ]);
        // 将生成好的select下拉框赋值到模板
        $this->view->assign('source', build_select('row[sourceid]', $source, $business['sourceid'], ['class' => 'form-control selectpicker']));
        return $this->view->fetch();
    }
}
